import {defineStore} from 'pinia'
import router from "@/router";
import {getAvatar, getUserInfo} from "@/api/user";

type Permissions = {
    [key: string]: boolean;
};
export const useLoginStore = defineStore('usersLogin', () => {
    let menus = reactive([])
    const userName = ref('')
    const avatar = ref('')
    const buttonPermissions = reactive<Permissions>({})
    const isCollapse = ref(false)
    const imageUrl = ref('');
    // 获取用户信息
    const getUserInfoFun = async () => {
        try {
            const res = await getUserInfo();
            if (res.code === 200) {
                menus.length = 0;
                menus.push(...res.data.routes);
                userName.value = res.data.userInfo.userName;
                avatar.value = res.data.userInfo.avatar;
                addDynamicRoutes(menus);
                Object.keys(buttonPermissions).forEach(key => {
                    delete buttonPermissions[key];
                });
                res.data.buttons.forEach((permission: any) => {
                    buttonPermissions[permission] = true;
                })
                return 'ok';
            } else {
                ElMessage.error(res.msg);
                return Promise.reject(new Error(res.msg));
            }
        } catch (error) {
            return Promise.reject(error); // 返回一个 Promise.reject()
        }
    }

    // 动态添加路由的函数
    function addDynamicRoutes(menuData: any) {
        const modules = import.meta.glob('@/views/**/*.vue');

        function generateRoutes(data: any) {
            return data.reduce((acc: any, item: any) => {
                if (item.children && item.children.length > 0) {
                    // 如果有 children，只处理子项
                    const subRoutes = generateRoutes(item.children);
                    acc.push(...subRoutes);
                } else {
                    // 如果没有 children，表示是路由
                    const route = {
                        path: item.path.startsWith('/') ? item.path : `/${item.path}`,
                        name: item.name,
                        component: modules[`/src${item.component}`],
                        meta: item.meta
                    };
                    acc.push(route);
                }
                return acc;
            }, []);
        }

        const dynamicRoutes = generateRoutes(menuData);
        dynamicRoutes.forEach((route: any) => router.addRoute('Layout', route));
    }

    const fetchImage = async () => {
        if (avatar.value == "") return;
        try {
            const response = await getAvatar(avatar.value);
            imageUrl.value = URL.createObjectURL(response);
        } catch (error) {
            console.error('Failed to fetch image:', error);
        }
    };
    // 退出登录
    const logout = () => {
        //清除所有缓存
        localStorage.clear();
        // 清除动态路由
        router.getRoutes().forEach((route: any) => {
            if (route.meta && route.meta.isDynamicRoute) {
                router.removeRoute(route.name);
            }
        });
        // 清除菜单
        menus.splice(0);
    }
    return {menus, isCollapse, userName, avatar, getUserInfoFun, logout, imageUrl, fetchImage, buttonPermissions}
})
